<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 导入axios -->
    <script src="./node_modules/axios/dist/axios.js"></script>
    <style>
        body {
            margin: 0;
            padding: 30px;

        }

        table,
        tr,
        th,
        td {
            border: 1px solid #000;
            /* 边框合并 */
            border-spacing: 0;
            border-collapse: collapse;
        }

        td,
        th {
            padding: 5px 10px;
        }

        a {
            text-decoration: none;
        }
    </style>
</head>

<body>
    <h1>用户列表</h1>
    <a href="./add.html">添加用户</a>
    <br><br>

    <table class="user-list">
        <tr>
            <th>id</th>
            <th>用户名</th>
            <th>密码</th>
            <th>操作</th>
        </tr>

        <!-- <tr> -->
            <!-- <td>1</td>
            <td>张三</td>
            <td>123</td>
            <td>
                <a href="">编辑</a>
                <a href="">删除</a>
            </td>
        </tr>

        <tr>
            <td>2</td>
            <td>李四</td>
            <td>124</td>
            <td>
                <a href="">编辑</a>
                <a href="">删除</a>
            </td>
        </tr> -->


    </table>

    <script>
        //通过axios发送异步请求
        //GET http://localhost:3000/users

        axios.get('http://localhost:3000/users').then(res => {
            console.log(res.data)

            res.data.forEach(item => {
                //获取table对象
                const table = document.querySelector('.user-list')
                // 根据item中的数据动态创建tr对象
                const tr = document.createElement('tr')
                tr.innerHTML = ` <tr>
                                    <td>${item.id}</td>
                                    <td>${item.username}</td>
                                    <td>${item.password}</td>
                                    <td>
                                        <a href="./edit.html?id=${item.id}">编辑</a>
                                        <a href="" onclick='handleDel(${item.id})'>删除</a>
                                    </td>
                                </tr>`
                //将tr添加到table中
                table.appendChild(tr)
            });
        })

        //实现删除方法
        function handleDel(id){
            axios.delete(`http://localhost:3000/users/${id}`).then(res =>{
                location.herf = './index.html'//刷新当前页面
            })
        }
    </script>
</body>

</html>